﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.WindowsAzure.ServiceRuntime;
using nwrole.lib;

namespace nwrole.Orchestrator.site {
    public class WebRole : RoleEntryPoint {

        //private volatile bool running = false;

        private AutoResetEvent waitEvent = new AutoResetEvent(false);

        public override bool OnStart() {
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            //running = true;

            return base.OnStart();
        }

        public override void Run() {
            // This is a sample worker implementation. Replace with your logic.
            //Trace.WriteLine("WorkerRole1 entry point called", "Information");

            string sbIssuerName = RoleEnvironment.GetConfigurationSettingValue("OrchestratorSBIssuerName");
            string sbIssuerSecret = RoleEnvironment.GetConfigurationSettingValue("OrchestratorSBIssuerSecret");

            lib.Orchestrator orchestrator = new lib.Orchestrator();
            orchestrator.Start(sbIssuerName, sbIssuerSecret);

            waitEvent.WaitOne();
            /*while (running) {
                Thread.Sleep(1000);
                //Trace.WriteLine("Working", "Information");
            }*/

            orchestrator.Stop();

            Thread.Sleep(Timeout.Infinite); // Don't ever return. If you do, the role will restart.
        }

        public override void OnStop() {
            waitEvent.Set();
            base.OnStop();
        }
    }
}